/*
 * @Author: Jone XIn
 * @Date: 2022-01-10 22:40:27
 * @LastEditTime: 2022-01-28 20:35:22
 * @Description: 设备信息操作类
 */
const { getLocalIp, formatDate } = require('../utils/tools');
const path = require('path');
const fs = require('fs-extra');
const { db_config, web_socket_config } = require('../config.json');
const dbInstance = require('../db/db');
const seq = dbInstance.getSequelizeInstance(db_config);
const { Project } = require('../model/project');
const { Room } = require('../model/room');
const { Device } = require('../model/device');
const { cerateRoomId } = require('../utils/uuid');
const Watcher = require('../lib/watcher');
const WsClient = require('../lib/ws_client');

let sync_id = '';
let project_name = '';
let project_path = '';
let watcher = '';
let wsClient = null;
/**
 * 返回房间列表
 * @param {*} req
 * @param {*} res
 */
const getOnlineProject = async (req, res) => {
    console.log(req.url);
    try {
        let result = await seq.query(`select * from project order by uid desc`, { type: seq.QueryTypes.SELECT });
        return res.json({ code: 200, data: result, message: '请求成功!' });
    } catch (_) {
        console.log(_);
        res.json({
            code: 500,
            data: null,
            message: _
        });
    }

}
/**
 * 返回本机IP和mid 并插入数据库
 * @param {*} req
 * @param {*} res
 */
const getDeviceInfo = async (req, res) => {
    console.log(req.url);
    try {
        // 获取本机Ip，获取m_id
        const localIp = getLocalIp();
        // 获取本机m_id
        const buffer = fs.readFileSync(path.join(__dirname, '../.m_id'))
        await Device.addDevice({
            ip: localIp,
            m_id: buffer.toString(),
            gen_time: formatDate(Date.now())
        });
        res.json({
            code: 200,
            data: { ip: localIp, mid: buffer.toString() },
            message: '请求成功'
        })
    } catch (_) {
        console.log(_);
        res.json({
            code: 500,
            data: null,
            message: _
        });
    }

}
/**
 * 创建房间
 * @param {*} req
 * @param {*} res
 */
const addRoom = async (req, res) => {
    console.log(req.url);
    try {
        const { project_path, m_id } = req.body.data;

        // 判断路径是否存在
        if (!fs.pathExistsSync(project_path)) return res.json({ code: 401, data: '', message: 'project路径不存在!' })
        const project_name = path.basename(project_path);

        // 判断房间是否重复存在
        const pInfos = await seq.query(`select * from project where m_id = "${m_id}" and project_name = "${project_name}"`, { type: seq.QueryTypes.SELECT })
        if (pInfos.length) return res.json({ code: 401, data: '', message: '此项目已存在!' })

        const roomId = cerateRoomId();
        const projectInfo = {
            project_name,
            project_path,
            m_id,
            sync_id: roomId,
            gen_time: Date.now()
        }

        // 注册并加入房间
        addDeviceInfo(projectInfo, async result => {
            if (result) {
                // 写入数据库
                // await Project.addProject(projectInfo);
                return res.json({ code: 200, data: '', message: '请求成功' });
            }
            res.json({ code: 500, data: '', message: '服务器内部错误' });
        });
    } catch (_) {
        console.log(_);
        res.json({ code: 500, data: null, message: _ });
    }

}
/**
 * 加入房间
 * @param {*} req 
 * @param {*} res 
 */
const joinRoom = async (req, res) => {
    console.log(req.url);
    try {
        const { m_id, sync_id, project_path } = req.body.data;

        // 判断路径是否存在
        if (!fs.pathExistsSync(project_path)) return res.json({ code: 401, data: '', message: 'project路径不存在!' })

        const project_name = path.basename(project_path);

        // 查看本设备是否已经是成员
        let result = await seq.query(`select * from project where m_id = "${m_id}" and sync_id = "${sync_id}"`, { type: seq.QueryTypes.SELECT });
        if (result.length) return res.json({ code: 400, data: '', message: '此项目正在您的设备运行!' })

        // 查看项目名称是否统一
        let pNames = await seq.query(`select project_name from project where sync_id = "${sync_id}" limit 1`, { type: seq.QueryTypes.SELECT });
        if (!pNames.length || pNames[0].project_name != project_name) return res.json({ code: 400, data: '', message: '请输出正确的项目名称' });
        const projectInfo = {
            project_name,
            project_path,
            sync_id,
            m_id,
            gen_time: Date.now()
        }
        // 加入房间
        addDeviceInfo({ project_name, project_path, sync_id }, async result => {
            if (result) {
                // 写入数据库
                // await Project.addProject(projectInfo);
                return res.json({ code: 200, data: '', message: '请求成功' });
            }
            res.json({ code: 500, data: '', message: '服务器内部错误' });
        });
    } catch (_) {
        console.log(_);
        res.json({ code: 500, data: null, message: _ });
    }
}

// 注册任务
const addDeviceInfo = async (inspectInfo, callback) => {
    // 实例化ws客户端
    wsClient = new WsClient(web_socket_config.ip, web_socket_config.port, () => {
        // 注册房间
        callback(wsClient.registRoomId(inspectInfo));
    });
}

module.exports = {
    getDeviceInfo,
    getOnlineProject,
    addRoom,
    joinRoom,
    addDeviceInfo
};